package cn.market.service.product.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.market.bean.QueryResult;
import cn.market.bean.product.BrandType;
import cn.market.service.base.DaoSupport;
import cn.market.service.product.BrandTypeService;
@Service
@Transactional
public class BrandTypeServiceBean extends DaoSupport<BrandType> implements
		BrandTypeService {


	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
	public List<Integer> getSubTypeid(Integer[] parentids){
		if(parentids!=null && parentids.length>0){
			StringBuffer jpql = new StringBuffer();
			for(int i=0; i<parentids.length; i++){
				jpql.append('?').append((i+1)).append(',');
			}
			jpql.deleteCharAt(jpql.length()-1);
			Query query = em.createQuery("select o.typeid from BrandType o where o.parent.typeid in("+ jpql.toString()+ ")");
			for(int i=0; i<parentids.length; i++){
				query.setParameter(i+1, parentids[i]);
			}
			return query.getResultList();
		}
		return null;
	}
	
	@Override
	public void delete(Serializable ... entityids) {
		if(entityids!=null && entityids.length>0){
			StringBuffer jpql = new StringBuffer();
			for(int i=0 ;i<entityids.length;i++){
				jpql.append("?").append(i+2).append(",");
			}
			jpql.deleteCharAt(jpql.length()-1);
			Query query = em.createQuery("update BrandType o set o.visible=?1 where o.typeid in("+ jpql.toString()+")")
			.setParameter(1, false);
			for(int i=0 ;i<entityids.length;i++){
				query.setParameter(i+2, entityids[i]);
			}
			query.executeUpdate();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public BrandType findParentByTypeid(Integer id) {
		String sql = "select typeid,name,note,sort,visible,parentid from brandtype where typeid=:typeid";
		SQLQuery query  = super.getSession().createSQLQuery(sql);
		query.setParameter("typeid", id);
		List list = query.list();
		return getBrandTypeInfo(list);
	}
	
	@SuppressWarnings("unchecked")
	private BrandType getBrandTypeInfo(List list){
		BrandType brand = new BrandType();
		if(list != null && list.size() > 0){
			for(int i = 0;i<list.size();i++){
				Object [] obj = (Object [])list.get(i);
				brand.setTypeid(new Integer(String.valueOf(obj[0])));
				brand.setName(String.valueOf(obj[1]));
				brand.setNote(String.valueOf(obj[2]));
				brand.setSort(new Integer(String.valueOf(obj[3])));
				brand.setVisible(Boolean.valueOf(String.valueOf(obj[4])));
				Integer parentid = null;//new Integer(String.valueOf(obj[5]));
				try{
					parentid = Integer.parseInt(String.valueOf(obj[5]));
				}catch(NumberFormatException e){
					parentid = null;
				}
				if(parentid != null && parentid > 0){
					BrandType parent = new BrandType();
					parent.setTypeid(parentid);
					brand.setParent(parent);
				}
			}
		}
		return brand;
	}

	@Override
	public BrandType findBrandTypeAndParentInfoByTypeid(Integer id) {
		BrandType type = this.findParentByTypeid(id);
		if(type.getParent() != null){
			BrandType parent = this.findParentByTypeid(type.getParent().getTypeid());
			type.setParent(parent);
		}
		return type;
	}

	@Override
	public void editBrandType(BrandType type) {
		StringBuffer sql =new StringBuffer( "update brandtype t " +
				" set t.name=:name,t.note=:note");
		if(type != null ){
			if(type.getParent() != null && type.getParent().getTypeid()>0)
				sql.append(",t.parentid=:parentid ");
			sql.append(" where t.typeid=:typeid");
			SQLQuery query = super.getSession().createSQLQuery(sql.toString());
			query.setParameter("name", type.getName());
			query.setParameter("note", type.getNote());
			if(type.getParent() != null && type.getParent().getTypeid()>0){
				query.setParameter("parentid", type.getParent().getTypeid());
			}
			query.setParameter("typeid", type.getTypeid());
			query.executeUpdate();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public QueryResult<BrandType> getBrandTypeSelectUI(String where, int first,
			int max, Object[] params, LinkedHashMap<String, String> orderby) {
		QueryResult<BrandType> qr = new  QueryResult<BrandType>();
		List<BrandType> types = new ArrayList<BrandType>();
		String sql = "select typeid,name from brandtype "+where;
		SQLQuery query = super.getSession().createSQLQuery(sql);
		if(params !=null && params.length>0){
			for(int i=0;i<params.length;i++)
				query.setParameter(String.valueOf(i+1), params[i]);
		}
		List list = query.list();
		if(list != null && list.size()>0){
			StringBuffer sql2 = new StringBuffer("select brandtypeid from brand where brandtypeid in (");
			Object [] params2 = new Object[list.size()];
			for(int i=0;i<list.size();i++){
				BrandType type = new BrandType();
				Object [] obj =(Object []) list.get(i);
				type.setTypeid(new Integer(String.valueOf(obj[0])));
				type.setName(String.valueOf(obj[1]));
				types.add(type);
				sql2.append(":").append(i+1).append(",");
				params2[i]=type.getTypeid();
			}
			sql2.deleteCharAt(sql2.length()-1);
			sql2.append(")");
			SQLQuery query2 = super.getSession().createSQLQuery(sql2.toString());
			for(int i=0;i<list.size();i++){
				query2.setParameter(String.valueOf(i+1), params2[i]);
			}
			List childs = query2.list();
			if(childs != null && childs.size()>0){
				for(int j=0;j<childs.size();j++){
					//Object obj [] = (Object [])childs.get(j);
					int typeid = new Integer(String.valueOf(childs.get(j)));
					System.out.println("this is childs loop");
					for(int x=0;x<types.size();x++){
						System.out.println("types.get(x).getTypeid() is:"+types.get(x).getTypeid()+";  the typeid is:"+typeid);
						int types_id = types.get(x).getTypeid();
						if(types_id == typeid){
							System.out.println("this typeid = sql query typeid");
							types.get(x).getChildtypes().add(new BrandType());
						}
					}
				}
			}
		}
		qr.setTotalrecord(super.getCount());
		qr.setResultlist(types);
		return qr;
	}
	
}
